控制器中间件
控制器中间件
V5.1.17+版本开始,支持为控制器定义中间件。首先你的控制器需要继承系统的think\Controller类,然后在控制器中定义middleware属性,例如:
phpnamespace app\index\controller;use think\Controller;class Index extends Controller{protected $middleware = ['Auth'];public function index(){return 'index';}public function hello(){return 'hello';}}
当执行index控制器的时候就会调用Auth中间件,一样支持使用完整的命名空间定义。
如果需要设置控制器中间的生效操作,可以如下定义:
phpnamespace app\index\controller;use think\Controller;class Index extends Controller{protected $middleware = ['Auth' => ['except' => ['hello'] ],'Hello' => ['only' => ['hello'] ],];public function index(){return 'index';}public function hello(){return 'hello';}}
控制器传参
可以通过给请求对象赋值的方式传参给控制器(或者其它地方),例如
phpnamespace app\http\middleware;class Hello{public function handle($request, \Closure $next){$request->hello = 'ThinkPHP';return $next($request);}}
注意,传递的变量名称不要和
param变量有冲突。
然后在控制器的方法里面可以直接使用
public function index(Request $request){return $request->hello; // ThinkPHP}